<template>
<Card class="viewAnchor" dis-hover>
    <a :class="{ active: anchor.isActive }" :href="anchor.hash" v-for="anchor in data" :key="anchor.hash" v-on:click.stop.prevent="scrollTo(anchor)">{{anchor.title}}</a>
</Card>
</template>

<script>
export default {
    props: {
        links: {
            type: Array
        }
    },
    data() {
        return {
            data: [],
            currentLink: {}
        }
    },
    methods: {
        getOffset(el) {
            var _x = 0,
                _y = 0;
            while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
                _x += el.offsetLeft - el.scrollLeft;
                _y += el.offsetTop - el.scrollTop;
                el = el.offsetParent;
            }
            return {
                top: _y,
                left: _x
            };
        },

        scrollTo(anchor) {
            document.documentElement.scrollTop = anchor.offsetTop - 60
        },

        handleScroll() {
            let top = window.scrollY
            let bottom = window.scrollY + document.body.clientHeight

            this.data.map((anchor, index, arr) => {
                if (anchor.offsetTop > top && anchor.offsetTop < bottom) {
                    anchor.isActive = true
                } else {
                    anchor.isActive = false
                }
            })
        }
    },
    mounted() {
        this.data = []
        setTimeout(() => {
            let that = this

            let fieldCards = document.querySelectorAll(".FieldsCard")
            fieldCards.forEach((value, index, array) => {
                that.data.push({
                    title: value.querySelector("h3").innerText,
                    hash: value.querySelector(".ivu-card-head a").hash,
                    offsetTop: that.getOffset(value).top,
                    isActive: false
                })
            })

            this.handleScroll()
        }, 1000)

        window.addEventListener("scroll", this.handleScroll)
    },
    beforeDestroy() {
        window.removeEventListener("scroll", this.handleScroll)
    }
}
</script>

<style lang="less" scoped>
.viewAnchor {
    border-radius: 0px;
    position: fixed;
    z-index: 999;
    top: 50px;
    bottom: 0px;
    right: 10px;
    width: 230px;
    // max-height: calc(100% - 85px);
    border-top: 0px;
    border-bottom: 0px;
    border-right: 0px;
    overflow: auto;

    a {
        color: #222;
        display: block;
        margin-bottom: 10px;

        &:last-child {
            margin-bottom: 0px;
        }

        &:hover {
            color: @link-hover-color;
        }

        &.active {
            color: @link-active-color;
        }
    }
}
</style>
